{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Validate Balanced Parentheses\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/PW7Lqurlde-xTyatiJUlGQ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given a string containing just the characters `(`,  `)`,  `{`,  `}`,  `[` and `]`,  determine if the input string is valid. \n",
    "\n",
    "An input string is valid if:\n",
    "\n",
    "- Open brackets are closed by the same type of brackets.\n",
    "- Open brackets are closed in the correct order.\n",
    "- An empty string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def validation(brackets: str) -> bool:\n",
    "\n",
    "    # Define a dictionary to attach the bracket pairs.\n",
    "    pairs = {\n",
    "        '}': '{',\n",
    "        ']': '[',\n",
    "        ')': '('\n",
    "    }\n",
    "\n",
    "    # Create a stack to record unclosed brackets.\n",
    "    stack = list()\n",
    "\n",
    "    # Traverse all characters in the string.\n",
    "    for k in brackets:\n",
    "\n",
    "        # If the current characters closes the nearest bracket,\n",
    "        # remove it from the stack, representing it is closed.\n",
    "        if len(stack) > 0 and k in pairs.keys() and pairs[k] == stack[-1]:\n",
    "            stack.pop()\n",
    "            pass\n",
    "\n",
    "        # Otherwise, push the current characters into the stack,\n",
    "        # and mark them unclosed.\n",
    "        else:\n",
    "            stack.append(k)\n",
    "            pass\n",
    "        pass\n",
    "\n",
    "    # If input string is valid,\n",
    "    # there's no unclosed characters remained in the stack.\n",
    "    return len(stack) == 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(validation(r''))\n",
    "print(validation(r'([{}])'))\n",
    "print(validation(r'(){}[]'))\n",
    "print(validation(r'{](}[)'))\n",
    "print(validation(r')]}'))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
